package work.huangxin.share.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;

/**
 * @author: 张锦标
 * @date: 2023/4/24 18:43
 * JsonConfig类
 */
@Configuration
public class JsonConfig implements WebMvcConfigurer {

    private static final Logger LOGGER = LoggerFactory.getLogger(JsonConfig.class);

    @Override

    public void addInterceptors(InterceptorRegistry registry) {

//请求上下文初始化拦截器配置

        LOGGER.info("初始化拦截器完成.....");

    }

    @Override

    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("swagger-ui.html")

                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")

                .addResourceLocations("classpath:/META-INF/resources/webjars/");

    }

    @Bean
    public ObjectMapper jacksonObjectMapperCustomization() {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        TimeZone timeZone = TimeZone.getTimeZone("Asia/Shanghai");

        format.setTimeZone(timeZone);

        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()

                .timeZone(timeZone)

                .dateFormat(format);

        return builder.build();

    }


    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.removeIf(c -> c instanceof MappingJackson2HttpMessageConverter);

        converters.add(new MappingJackson2HttpMessageConverter(jacksonObjectMapperCustomization()));
    }

}
